You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中如何在main函数内创建类内部结构体的实例?

在C++中直接在main函数创建类内部结构体的实例

当然可以,因为你定义的elephant是ABC类的public成员结构体,外部代码可以通过类作用域解析符::直接访问这个结构体类型,进而创建它的实例。

你的现有代码是通过ABC类的对象i访问已有的instance成员,而不是创建新的elephant实例。要在main里直接创建新的实例,只需要用ABC::elephant来声明变量即可,示例代码如下:

#include <string>
#include <iostream>

using namespace std;

class ABC {
    private:
        string name, f_name, session, cls, dob;

    public:
        struct elephant {
            string x, y, z;
        };

        elephant instance;
        elephant a;

        ABC() {
            cout << "the default constructor" << endl;
        }
};

int main()
{
   ABC i;
   i.instance.x = "We"; // 访问ABC对象已有的elephant成员

   // 直接在main里创建新的elephant实例
   ABC::elephant newElephant;
   newElephant.x = "Hello";
   newElephant.y = "World";
   cout << newElephant.x << " " << newElephant.y << endl;

   return 0;
}

注意:如果elephant结构体被声明为ABC的private或protected成员,那么外部(比如main函数)就无法直接访问和创建它的实例了,只有ABC类内部以及它的子类(protected场景)才能使用。

内容的提问来源于stack exchange,提问作者Ignatius Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 10:42:07