在我的C ++程序中,我有单独的.h和.cpp文件,到目前为止一切正常,除非我想为派生类使用基类构造函数。它正在工作,但只有当我放置函数定义时,如果类减速。 这是.h文件的工作代码。
#include <iostream>
using namespace std;
class property
{
public:
property();
property(const property & src);
property(int src);
~property();
virtual int disp() const = 0;
int get_ownable();
private:
protected:
int ownable;
};
class rr : public property
{
public:
rr();
rr(const rr & src);
rr(int src):property(src)
{cout << "\nderived class was called\n";};
~rr();
virtual int disp() const;
private:
protected:
};
imp.cpp(实现)文件是
#include "head.h"
#include <iostream>
using namespace std;
//property class implimentations
property::property()
{
ownable = 0;
}
property::property(const property & src)
{
ownable = src.ownable;
}
property::property(int src)
{
ownable = src;
cout << "\nparent class called\n";
}
property::~property()
{
}
int property::get_ownable()
{
return ownable;
}
rr::rr()
{}
rr::rr(const rr & src)
{
ownable = src.ownable;
}
/*
rr::rr(int src):property(src)
{
cout << "\nderived class was called\n";
}
*/
rr::~rr()
{
}
int rr::disp() const
{
}
还有其他代码,但它工作正常,没有连接到此。输出是
parent class called
derived class was called
这样工作正常但是如果我取消注释.imp文件中的函数并删除.h中的声明
rr(int src):property(src);
我收到错误
head.h: IN constructor 'rr::rr(int)':
head.h 113: error: expeted '{' at end of input
imp.cpp: at global scope:
imp.cpp:348:error: redefiniton of 'rr::rr(int);
head.h.113: error: 'rr::rr(int); previousle defined here
我可以在线上找到的所有示例都可以使用类声明中定义的所有函数来完成。我找不到任何有关如何使用2个文件的示例。谁能告诉我如何在单独的文件中定义基类构造函数调用? 我在使用g ++编译器的Linux系统上。
答案 0 :(得分:0)
喜欢这个
<强> BaseClass.h 强>
#pragma once
class BaseClass {
public:
BaseClass(int a);
private:
int a_private;
};
<强> BaseClass.cpp 强>
#include "BaseClass.h"
#include <iostream>
using std::cout;
using std::endl;
BaseClass::BaseClass(int a) {
cout << "Base class constructor called" << endl;
this->a_private = a;
}
<强> Derived.h 强>
#pragma once
#include "BaseClass.h"
class Derived : public BaseClass {
public:
Derived(int a);
private:
int a_private;
};
<强> Derived.cpp 强>
#include "Derived.h"
#include <iostream>
using std::cout;
using std::endl;
Derived::Derived(int a) : BaseClass(a) {
cout << "Derived class constructor called" << endl;
this->a_private = a;
}
<强>的main.cpp 强>
#include "BaseClass.h"
#include "Derived.h"
int main() {
Derived d(2);
return 0;
}
使用命令进行编译
g++ main.cpp Derived.cpp BaseClass.cpp
并且正在运行会产生以下输出
Base class constructor called
Derived class constructor called
如评论中所述(信用@IgorTandetnik),初始化列表应仅用于实现文件中。不在头文件中(假设类没有模板化)。