标签:
在规范c++编程时遇到的,即类的文件定义
常规的对类的使用,在class.h对类进行生命,对于成员函数在class.cpp中定义,如下实现
main.cpp #include<iostream> #include "person.h" using namespace std; int main() { person p; p.setage(12); cout<<p.backage()<<endl; return 0; }
person.h #ifndef _PERSON_H_ #define _PERSON_H_ class person { public: void setage(int n); int backage(); private: int age; }; #endif
person.cpp #include "person.h" void person::setage(int n) { age=n; } int person::backage() { return age; }
class person { public: inline void setage(int n); inline int backage(); private: int age; };
t.c文件 inline void f() { int a; a++; } int main() { f(); return 0; }
f: pushq %rbp movq %rsp, %rbp addl $1, -4(%rbp) popq %rbp ret main: pushq %rbp movq %rsp, %rbp movl $0, %eax call f movl $0, %eax popq %rbp ret
#include<stdio.h> inline int f(int a) { a++; printf("a=%d\n",a); return a; } int main() { int b=0; b=f(b); printf("b=%d\n",b); return 0; }汇编代码为
main: subq $8, %rsp movl $1, %edx movl $.LC0, %esi movl $1, %edi xorl %eax, %eax call __printf_chk movl $1, %edx movl $.LC1, %esi movl $1, %edi xorl %eax, %eax call __printf_chk xorl %eax, %eax addq $8, %rsp ret
inline function shall be defined in every translation unit in which it is used and shall have exactly the same definition in every case. 并且有人对此做了研究,下面是对话
> File1.cc: > ----------------snip here---------------- > inline int foo (int x) { return x; } > > int bar() { return foo(2); } > ----------------snip here---------------- > > File2.cc: > ----------------snip here---------------- > inline int foo (int); > > int main() { return foo(1); } > ----------------snip here---------------- > > If I compile this using "g++ File1.cc File2.cc" I get a working program > that returns 1. If I compile it with "-O" enabled, I get a linker error: > > Unresolved text symbol "foo(int)" -- 1st referenced by /var/tmp//cckhU7pa.o. > > Without optimization the function "foo" in the first file isn't inlined. > But because it's used by "bar" it is put in the object file. With optimization > the function is inlined and doesn't appear explicitly in the object file of > the first file. Therefore, the linker error. > > In essence: The compiler does not need to put inline functions in the object > file. The compiler can just optimize them away. And because of that we have > paragraph 7.1.2.4.
inline function shall be defined in every translation unit in which it is used and shall have exactly the same definition in every case. 并且有人对此做了研究,下面是对话
到此就明白了,在我上面的那个c++类中,如果main要调用内联的成员函数,那么在main所在的这个文件里必须要有内联函数的定义
所以修改为
main.cpp #include<iostream> #include "person.h" #include "person.cpp" using namespace std; int main() { person p; p.setage(12); cout<<p.backage()<<endl; return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/u010442328/article/details/47295409