码:
#include <cstdio>
class myc {
int dummy;
public:
int si(){return sizeof(*this);}
};
class d_myc : public myc {
int d_dummy;
};
int main() {
myc a;
d_myc b;
printf("%d %d\n%d %d", a.si(), b.si(), sizeof(a), sizeof(b));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
4 4
4 8
Run Code Online (Sandbox Code Playgroud)
我期望 :
4 8
4 8
Run Code Online (Sandbox Code Playgroud)
为什么我的期望错了?
我可以使用模板类的前向声明吗?
我尝试:
template<class que_type>
class que;
int main(){
que<int> mydeque;
return 0;
}
template<class que_type>
class que {};
Run Code Online (Sandbox Code Playgroud)
我明白了:
error: aggregate 'que<int> mydeque' has incomplete type and cannot be defined.
Run Code Online (Sandbox Code Playgroud) 码:
class que {
public:
que operator++(int) {} // 1
que &operator++() {}
que &operator+=(int n) {
que& (que::*go)();
go = 0; if(n > 0) go = &que::operator++ ; // 2
//go = (n > 0) ? (&que::operator++) : 0 ; // 3
}
};
int main() {
que iter;
iter += 3;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我想用第3行替换第2行("if:"语句为"?:").
如果我取消注释3,编译器会给我一个错误.
如果我删除第1行,则第3行有效.
问题是:编译器对我有什么要求?
错误:错误:没有上下文类型信息的重载函数的地址
编译器:gcc-4.5.2
如何从Super :: Super()调用Super :: printThree?
在下面的例子中,我改为调用Test :: printThree.
class Super {
Super() {
printThree(); // I want Super::printThree here!
}
void printThree() { System.out.println("three"); }
}
class Test extends Super {
int three = 3
public static void main(String[] args) {
Test t = new Test();
t.printThree();
}
void printThree() { System.out.println(three); }
}
output:
0 //Test::printThree from Super::Super()
3 //Test::printThree from t.printThree()
Run Code Online (Sandbox Code Playgroud)