可以在类之外定义构造函数吗?
Can the constructor be defined out of the class?
为什么gcc不能成功编译下面的代码?可以在类之外定义构造函数吗?
#include <string>
using std::string;
class Person{
public:
Person(const string &a, const string &b);
private:
string name, address;
};
Person::Person(const string &a, const string &b){
name(a);
address(b);
}
谢谢!
因为name
和address
都不可调用。您可能打算将它们放入成员初始化列表中。
Person::Person(const string &a, const string &b)
: name(a), address(b)
{
}
语法错误:
Person::Person(const string &a, const string &b) : name(a), address(b) {}
你写错了。应该是:
Person::Person(const string &a, const string &b) : name(a), address(b) { }
原则上,并且在实践中,您可以并且应该在类定义之外定义成员函数,以解耦代码库并减少编译时间。
这叫做实现和声明的分离。这实际上是一个好主意保持你的实现分开,在cc
或cpp
文件。
因此,在你的标题中:
//Person.h
#ifndef PERSON_H // <---- include header guards in your headers
#define PERSON_H
#include <string>
//using std::string; <--- you should remove this line, you don't want to import namespaces
// in your header file, or else they are imported in all
// files including this header
class Person{
public:
Person(const std::string &a, const std::string &b);
private:
std::string name, address; // qualify your names in the header
};
#endif
和你的实现文件:
//Person.cpp
#include "Person.h"
using namespace std; // <---- if you wish, import the std namespace in your global namespace
// in the implementation file
Person::Person(const string &a, const string &b):
name(a), // <---- correct syntax of initializer lists
address(b)
{
}
相关文章:
- 具有自定义构造函数 (C++) 的类型的动态数组分配
- 当类成员参数具有相同的名称时,如何定义构造函数?
- C++定义构造函数使对象成为非 POD
- 请描述一下在 c++ 中在此类中定义构造函数的方式?
- 不为 emplace() 定义构造函数的解决方法
- 已定义构造函数的构造函数无法识别
- 在自定义构造函数中的堆上创建指针
- c++ 17 中结构自动定义构造函数的规则是什么?
- Python 错误:在 SWIG 生成的C++模板化代码模块中没有定义构造函数
- unique_ptr看不到派生类的自定义构造函数
- 两种类型的定义构造函数有什么区别?第一个使用":",第二个用大括号(如函数)定义它
- 为什么一个非平凡的成员需要为同一类中的匿名联合定义构造函数
- 为其成员根据模板基类存在的类定义构造函数
- 如何在派生类上具有默认行为,而不是重新定义构造函数
- 在结构中定义构造函数
- 将从基类继承的构造函数与自定义构造函数混合使用
- 如何在模板类外部定义构造函数
- C 需要使用自定义构造函数的帮助
- 可以联合包含具有用户定义构造函数的类的对象
- 具有用户定义构造函数的非聚合类的值初始化