gpt4 book ai didi

c++ - 读取类变量

转载 作者:行者123 更新时间:2023-11-28 00:42:06 24 4
gpt4 key购买 nike

我创建了一个名为“Triangle”的类,现在正试图从主要部分中读出某个类变量(“SideA”)。我特别声明 SideA 为“公共(public)”以防止访问问题。但是,在尝试编译时,程序抛出错误“Triangle 类没有名为 SideA 的成员”。

我正在为您粘贴最重要的部分:

class Triangle
{
public:
float SideA;
};

int main ()
{
Triangle Object(); //pair is normally filled with several vars for the constructor)

//I declared "Object" correctly, it can be constructed. "SideA" is filled by the
//constructor. I'm just leaving it out
//right now to keep this text short

//This line is marked when the IDE aborts the compiling process
cout << Object.SideA;

我希望你能帮助我,因为我真的不知道如何解决这个问题。我正在学习的书籍建议为这些目的使用特殊函数(“void readOut {return X}”),但是每次我想读出一个数字时我真的必须编写一个函数吗?

先谢谢你,JustATestAcc

最佳答案

尝试更新

Triangle Object();  // This declares a function which returns Triangle type

Triangle Object;    // this defines Object

另请阅读 most vexing parse

如果你使用 C++11,你可以用 list initialization 初始化 Object

Triangle Object{};    // value-initialization (to zero)
Triangle Object{2.0}; // direct-list-initialization

关于c++ - 读取类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18355460/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com