c++ 带默认值的构造函数 定义与实现分离

本文讨论了C++中带有默认值参数的构造函数在定义和实现分离时遇到的问题。当在头文件stack.h中将构造函数定义为Stack(int ms = 0)并设置默认值,而在实现文件stack.cpp中尝试不使用默认值进行实现时,会导致编译错误。相反,如果在头文件中仅声明Stack(int ms),而在cpp文件中提供带有默认值的实现也会引发错误。
摘要由CSDN通过智能技术生成
//stack.h
#include <vector>
using namespace std;

template<class T>
class Stack{
private:
	int maxsize;
	int top;
	vector<T> vec;
public:
	Stack(int ms = 0);


};
//stack.cpp
#include "stack.h"

template<class T>
Stack<T>::
Stack(int ms):maxsize(ms){
    cout<<"get it"<<endl;
}
//main.cpp
<pre name="code" class="cpp">#include <iostream>
#include "stack.cpp"
using namespace std;

int main()
{
	Stack<int> s(2);
    Stack<int> s1;
	return 0;
}


 

采取上述方法定义的stack类构造函数可用。

当 stack.h 中构造函数定义更改为:

Stack(int);

同时,stack.cpp中实现改为:

Stack(int ms = 0):maxsize(ms){}时,报错。


将 stack.h 中构造函数定义更改为:

Stack(int ms = 0):maxsize(ms), top(-1);

stack.cpp 中实现改为:

Stack(int ms){...}

报错


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值