gpt4 book ai didi

c++ - 合格类(class)成员

转载 作者:行者123 更新时间:2023-11-30 00:35:31 26 4
gpt4 key购买 nike

我写了下面的代码:

class A
{
public:
int foo();
};

class B
{
public:
int A::foo(){ return 0; }; //error: non-friend class member 'foo' cannot have a qualified name
};

int main(){ }

为什么会导致这个错误?你能从标准中得到明确拒绝构造的引用吗?

最佳答案

int A::foo(){ return 0; };

Why does this error caused?

因为这在 C++ 中没有任何意义。这不是有效的构造。与此相关的是

C++ 标准 n3337 § 9.3 段成员函数

2) A member function may be defined (8.4) in its class definition, in which case it is an inline member func- tion (7.1.2), or it may be defined outside of its class definition if it has already been declared but not defined in its class definition. A member function definition that appears outside of the class definition shall appear in a namespace scope enclosing the class definition. Except for member function definitions that appear outside of a class definition, and except for explicit specializations of member functions of class templates and member function templates (14.7) appearing outside of the class definition, a member function shall not be redeclared.

3) An inline member function (whether static or non-static) may also be defined outside of its class definition provided either its declaration in the class definition or its definition outside of the class definition declares the function as inline. [ Note: Member functions of a class in namespace scope have external linkage. Member functions of a local class (9.8) have no linkage. See 3.5. — end note ]

4) There shall be at most one definition of a non-inline member function in a program; no diagnostic is required. There may be more than one inline member function definition in a program. See 3.2 and 7.1.2.

您应该问问自己,这应该是什么?你想达到什么目的?如果您的意图是覆盖它,您可以这样做:

class A
{
public:
virtual int foo() { return 3;}
};

class B : public A
{
public:
int foo() override { return 0; }
};

如果你想在 B 中使用 A::foo 则将 A::foo 设为静态

class A
{
public:
static int foo() { return 3;}
};

class B
{
public:
int bar()
{
int u = A::foo();
return u + 8 - 2;
}
};

或者在B中实例化A成员:

class A
{
public:
int foo() { return 3;}
};

class B
{
A a;
public:
int bar()
{
int u = a.foo();
return u + 8 - 2;
}
};

关于c++ - 合格类(class)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24345034/

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