C++ error: redefinition of `void Book:"

dai1992 2014-05-18 10:33:58
请大家帮忙看看错误在哪里,为什么我把类的成员函数的定义放在类的定义中就能通过,在类外编译就出现redefinition

C++编译错误
--------------------配置: mingw5 - CUI Debug, 编译器类型: MinGW--------------------

检查文件依赖性...
正在编译 C:\Users\leo\Desktop\学习代码 (4).cpp...
[Error] C:\Users\leo\Desktop\学习代码 (4).cpp:17: error: redefinition of `void Book::sale(int)'
[Error] C:\Users\leo\Desktop\学习代码 (4).cpp:12: error: `void Book::sale(int)' previously defined here
[Error] C:\Users\leo\Desktop\学习代码 (4).cpp:24: error: redefinition of `void Book::show()'
[Error] C:\Users\leo\Desktop\学习代码 (4).cpp:13: error: `void Book::show()' previously defined here
[Error] C:\Users\leo\Desktop\学习代码 (4).cpp:30: error: redefinition of `void Book::set(char*, int, int)'
[Error] C:\Users\leo\Desktop\学习代码 (4).cpp:14: error: `void Book::set(char*, int, int)' previously defined here
[Warning] C:\Users\leo\Desktop\学习代码 (4).cpp:43:2: warning: no newline at end of file

构建中止 学习代码 (4): 6 个错误, 1 个警告


代码:

#include<iostream>
using namespace std;

class Book{
private:
char *name;
int price;
int num;
public:
Book(char *na,int pr,int nu):name(na),price(pr),num(nu){}
Book():name("none"),price(0),num(0){}
void sale(int nu){}
void show(){}
void set(char *na,int pr,int nu){}
};

void Book::sale(int){
if(num<0)cout<<"sale out!";
else {num=num-nu;
cout<<"the sale money:"<<nu*price<<endl;
}
}

void Book::show(){
cout<<"the book's name:"<<name<<endl;
cout<<"the book's price:"<<price<<endl;
cout<<"the book's number:"<<num<<endl;
}

void Book::set(char*,int,int){
name=na;
price=pr,
num=nu;
}


int main()
{
Book Harry("harry",199,23);
Harry.show();
Harry.sale(12);
Harry.show();
}
...全文
1203 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
知行year 2014-05-18
  • 打赏
  • 举报
回复
修改如下: #include<iostream> using namespace std; class Book{ private: char *name; int price; int num; public: Book(char *na,int pr,int nu):name(na),price(pr),num(nu){} Book():name("none"),price(0),num(0){} void sale(int nu); void show(); void set(char *na,int pr,int nu); }; void Book::sale(int nu){ if(num<0)cout<<"sale out!"; else {num=num-nu; cout<<"the sale money:"<<nu*price<<endl; } } void Book::show(){ cout<<"the book's name:"<<name<<endl; cout<<"the book's price:"<<price<<endl; cout<<"the book's number:"<<num<<endl; } void Book::set(char *na,int pr,int nu){ name=na; price=pr; num=nu; } int main() { Book Harry("harry",199,23); Harry.show(); Harry.sale(12); Harry.show(); }
dai1992 2014-05-18
  • 打赏
  • 举报
回复
哥们 谢谢 发现了 加了{}是定义 不是声明
taodm 2014-05-18
  • 打赏
  • 举报
回复
void sale(int nu){} 兄弟,你知道后面的{}是个什么意思么。

65,208

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧