编程论坛
注册
登录
编程论坛
→
C++教室
类中哪些函数能设为内联函数?
feng00055
发布于 2010-08-09 15:27, 839 次点击
我在编写类时,有些函数能设为内联, 有些则报错“undefined reference to ‘……’”
请高手指点!谢谢
7 回复
#2
flyingcat
2010-08-09 18:45
- -内联函数,这个函数是反复多次被调用,为了提高程序的效率,会使用内联函数
不过内联函数的要求是,只能包含简单的运算(我记得代码最好也不要超过三行),什么循环、switch之类的都不能有,只能是简单的函数
你说的undefined reference to,应该是指后面那个变量未定义
#3
feng00055
2010-08-09 20:33
//stonewt.h
#ifndef STONEWT_H_
#define STONEWT_H_
class Stonewt {
private:
enum {Lbs_per_stn = 14};
int stone;
double pds_left;
double pounds;
public:
Stonewt(double lbs);
Stonewt(int stn, double lbs);
Stonewt();
~Stonewt();
void show_lbs()const;
void show_stn()const;
};
#endif
//stonewt.cc
#include <iostream>
#include "stonewt.h"
Stonewt::Stonewt(double lbs) {
stone = int(lbs) / Lbs_per_stn;
pds_left = int(lbs) % Lbs_per_stn + lbs - int(lbs);
pounds = lbs;
}
Stonewt::Stonewt(int stn, double lbs) {
stone = stn;
pds_left = lbs;
pounds = stn * Lbs_per_stn + lbs;
}
Stonewt::Stonewt() {
stone = pounds = pds_left = 0;
}
Stonewt::~Stonewt() {}
void Stonewt::show_stn()const {
std::cout << stone << " stone, " << pds_left << " pounds\n";
}
void Stonewt::show_lbs()const {
std::cout << pounds << " pounds\n";
}
#4
feng00055
2010-08-09 20:37
#include <iostream>
#include "stonewt.h"
void display(const Stonewt & st, int n);
int main(void) {
Stonewt pavarotti = 260;
Stonewt wolfe(285.7);
Stonewt taft(21, 8);
std::cout << "The tenor weighed ";
pavarotti.show_stn();
std::cout << "The detective weighted ";
wolfe.show_stn();
std::cout << "The President weighted ";
taft.show_lbs();
pavarotti = 265.8;
taft = 325;
std::cout << "After dinner, the tenor weighted ";
pavarotti.show_stn();
std::cout << "After dinner, the President weighed ";
taft.show_lbs();
display(taft, 2);
std::cout << "The wrestler weighed even more.\n";
display(422, 2);
std::cout << "No stone left unearned\n";
return 0;
}
void display(const Stonewt & st, int n) {
for (int i = 0; i < n; ++i) {
std::cout << "Wow! ";
st.show_stn();
}
}
#5
feng00055
2010-08-09 20:40
stonewt.cc中除了没用到的Stonewt()外, 为什么全都不能设置为内联函数?
#6
feng00055
2010-08-09 21:53
对不起, 是我搞错了:内联函数要求在每个使用它们的文件中
都对其进行定义,而我却把它们放到了不是头文件的文件中,在主函数
文件中又没包含它们,所以才出错!
原来是我概念没弄清楚!
#7
feng00055
2010-08-09 21:55
多谢2楼,虽没有提到这点, 所以给你10分吧!
#8
feng00055
2010-08-09 21:58
给不了10, 给20吧
1