int a[3][4] = {{1,2,3,4}, {5, 6, 7, 8}, {8, 10, 11, 12}};
cout << a[2][1] << endl;
cout << *(a[2] + 1) << endl;
cout << *(*(a + 2) + 1) << endl;
int a[10] = {1,2,3,4,5,6,7,8,9,10};
int* p1 = &a[0];
int* p2 = &a[9];
printf("%d",p1 - p2);
#define BUFFSIZE 10
int a[BUFFSIZE];
extern int getdata();
int main(){
int* buf = a;
while(buf < sizeof(a)){
*buf++ = getdata();
}
}
找错,博主本人C++基础也不是很好,如果指出有错误,欢迎评论区讨论。
#define BUFFSIZE 10
int a[BUFFSIZE];
extern int getdata();
int getdata(){
static int i = 0;
return i++;
}
int main(){
int* buf = a;
while(buf < sizeof(a)){ // buf != &a[BUFFSIZE]
*buf++ = getdata();
}
for(int i = 0; i < 10; ++i){
cout << a[i] << endl;
}
}
// 首先sizeof(a)不是数组的长度,其次buf是地址不可以和长度比较
借助这个题目理清C++多态机制。
class book{
public:
virtual void bookname(){
cout << "this is book,";
getpage();
}
virtual void getpage(){
cout << "30 pages" << endl;
}
};
class englishbook:public book{
public:
virtual void bookname(){
cout << "this is englishbook,";
getpage();
}
virtual void getpage(){
cout << "50 pages" << endl;
}
};
int main(){
englishbook* engbook = new englishbook(); // 子类指针指向子类对象
book* book1 = (book*)engbook; // 父类指针指向子类对象
book* book2 = new book(); // 父类指针指向父类对象
book* book3 = new englishbook(); // 父类指针指向子类对象
englishbook* engbook2 = (englishbook*)book2; // 子类指针指向父类对象
book3->bookname();
book2->bookname();
book1->bookname();
engbook->bookname();
engbook2->bookname();
return 0;
/*
this is englishbook,50 pages
this is book,30 pages
this is englishbook,50 pages
this is englishbook,50 pages
this is book,30 pages
*/
}
百度的一个选择题,考察的是函数匹配优先级的。
自己实现了一下,发现…的匹配度优先级是最低的。
#include <bits/stdc++.h>
#include <cassert>
using namespace std;
class test{
public:
test(int) {}
};
template <typename T>
void* Is_pointer(T* p){
return nullptr;
}
int Is_pointer(...){
return 0;
}
template<typename T>
char Is_pointer(T p){
return 'x';
}
int main() {
test t(0);
test *pt = &t;
int i = 0;
int *pi = &i;
cout << sizeof(Is_pointer(t)) << endl;
cout << sizeof(Is_pointer(pt)) << endl;
cout << sizeof(Is_pointer(i)) << endl;
cout << sizeof(Is_pointer(pi)) << endl;
}
如果将形参为T* p的函数注释掉:
如果再将形参为T p的函数注释掉:
**strlen (字符指针表达式)**计算给定字符串的(unsigned int型)长度,不包括’\0’在内。
‘\’转义符号,所以\t,",\065,\xff,\n都是作为一个考虑
printf("%d\n", (int)strlen("\t\"\065\xff\n"));
// 5
小红书测开的一个C++程序题,考察的是类指针和类对象。
class Animal{
public:
virtual void sleep(){
cout << "Animal sleep\n";
}
};
class Cat : public Animal{
public:
virtual void sleep(){
cout << "Cat sleep\n";
}
void func(){
sleep();
}
};
class Tiger : public Cat{
public:
virtual void sleep(){
cout << "Tiger sleep\n";
}
};
int main(){
Tiger t;
((Cat *)(&t))->func();
((Cat)t).func();
return 0;
}
比较常规的题目,因为类指针才会有多态,所以第一个输出是Tiger sleep, 第二个输出是Cat sleep.