gpt4 book ai didi

C++ 从 protected 抽象/派生类创建变量

转载 作者:行者123 更新时间:2023-11-28 04:29:02 27 4
gpt4 key购买 nike

我想弄清楚从派生类创建变量时哪里出错了。我有抽象类、派生类,并试图在主测试程序中将派生类创建为变量。但是我得到错误:没有匹配函数调用 DerivedPlayer::DerivedPlayer()’。我一直无法找到创建和初始化派生类变量的正确语法。另请注意,抽象类的构造函数是 protected 。

抽象 header (Base.h)

    #ifndef BASE_H_
#define BASE_H_

#include <iostream>
#include <vector>

class Base {
public:
virtual ~Base() {}

protected:
Base(std::string s) : x(0), s(s), v(0) {}

int x;
std::string s;
std::vector<int> v;
};
#endif

派生头文件(Derived.h)

    #ifndef DERIVED_H_
#define DERIVED_H_

#include "Base.h"

class Derived : public Base {
public:
Derived(std::string name){ s = name; }
virtual ~Derived();
};

#endif

测试代码(InTest.cpp)

    #include <iostream>
#include "Derived.h"

int main() {

Derived a = Derived("R2-D2");
Derived b = Derived("C-3PO");

return 0;
}

构建日志

    03:23:52 **** Incremental Build of configuration Debug for project InTest ****
make all
Building file: ../src/InTest.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/InTest.d" -MT"src/InTest.o" -o "src/InTest.o" "../src/InTest.cpp"
In file included from ../src/InTest.cpp:2:0:
../src/Derived.h: In constructor ‘Derived::Derived(std::string)’:
../src/Derived.h:8:27: error: no matching function for call to ‘Base::Base()’
Derived(std::string name){ s = name; }
^
../src/Derived.h:8:27: note: candidates are:
In file included from ../src/Derived.h:4:0,
from ../src/InTest.cpp:2:
../src/Base.h:12:2: note: Base::Base(std::string)
Base(std::string s) : x(0), s(s), v(0) {}
^
../src/Base.h:12:2: note: candidate expects 1 argument, 0 provided
../src/Base.h:7:7: note: Base::Base(const Base&)
class Base {
^
../src/Base.h:7:7: note: candidate expects 1 argument, 0 provided
make: *** [src/InTest.o] Error 1

03:23:52 Build Finished (took 214ms)

最佳答案

错误信息的主要部分如下:

../src/Derived.h: In constructor ‘Derived::Derived(std::string)’:
../src/Derived.h:8:27: error: no matching function for call to ‘Base::Base()’
Derived(std::string name){ s = name; }

因为Derived继承自Base,每次构造Derived对象时,Base类的构造函数也有运行。您当前代码的问题是您让默认的 Base 构造函数被调用,但实际上没有。

您通过“调用”Derived 构造函数初始化列表中正确的Base 构造函数来解决它:

Derived::Derived(std::string name)
: Base(name)
{}

关于C++ 从 protected 抽象/派生类创建变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53466688/

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