gpt4 book ai didi

请求成员函数时出现C++错误

转载 作者:太空狗 更新时间:2023-10-29 20:13:14 26 4
gpt4 key购买 nike

我有这样一个类

class action {
int val;
// some other members
public:
action() : val(0) { } // default constructor initializes action type to 0
action(int val) : val(val) { }
// some other member functions
int getVal() { return val; }
};

以及在简单场景下使用时

action obj1(), obj2(2);
cout << "Initial state : { " << obj1.getVal() << ", " << obj2.getVal() << " }\n";

编译出错

error: request for member ‘getVal’ in ‘obj1’

这是怎么回事?

最佳答案

那是因为您没有声明action类型的obj1

action obj1()

声明了一个函数 obj1,它不接受任何参数并返回一个 Action 对象。更喜欢 c++11 大括号初始化来调用默认构造函数

action obj1{}

或者只是不使用那些额外的括号。

这个问题你可以google一下,因为c++ most vexing parse

关于请求成员函数时出现C++错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22628835/

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