一、c聲明變數
c語言中,聲明變數需要指定變數的類型,在變數名前添加數據類型。如:
int a; float b; char c;
在C++中,與C語言相同,變數的聲明同樣需要指定類型,但更支持各種自定義類型的聲明。如:
#include <iostream>
using namespace std;
struct Student {
int id;
string name;
int age;
};
int main() {
int a;
float b;
char c;
Student stu;
return 0;
}
二、c聲明兩個變數值相同
在C語言中,如需將一個變數賦值給另一個變數,需要這樣寫:
int a = 1; int b = a;
而在C++中,可以這樣寫:
int a = 1;
int b{ a };
三、c聲明賦值
C語言中,為變數賦值需要使用賦值符(=)。如:
int a; a = 10;
而在C++中,可以在聲明時進行初始化賦值。如:
int a = 10;
也可以使用賦值符(=)進行賦值。如:
int a; a = 10;
四、聲明抽象類的引用並將c賦給a
在C++中,可以使用純虛函數實現抽象類。如:
class Shape {
public:
virtual void show() = 0;
};
class Circle : public Shape {
public:
void show() override {
cout << "This is a circle." << endl;
}
};
int main() {
Shape* c = nullptr;
Circle circle;
c = &circle;
return 0;
}
在上面的例子中,聲明一個抽象類Shape,並生成一個Circle派生類。將Circle的指針賦值給Shape指針c,以此完成將c賦給a的過程。
五、c聲明對象
C語言中沒有對象的概念,但C++中支持面向對象編程,可以定義類和對象。如:
#include <iostream>
using namespace std;
class Student {
public:
string name;
int age;
void showInfo() {
cout << "Name: " << name << " Age: " << age << endl;
}
};
int main() {
Student stu;
stu.name = "Tom";
stu.age = 18;
stu.showInfo();
return 0;
}
在上面的例子中,定義一個Student類,類中包含姓名和年齡兩個屬性以及列印信息的方法showInfo()。在main函數中聲明一個stu對象,並對其屬性進行賦值,最後列印出對象的信息。
六、c聲明string長度
在C語言中不支持字元串類型,需要使用字元數組來表示。可以通過strlen()函數獲取字元串長度。如:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello World";
int len = strlen(str);
printf("String length is %d.\n", len);
return 0;
}
而在C++中,可以使用string類型來表示字元串,並使用其內置函數size()獲取長度。
#include <iostream>
using namespace std;
int main() {
string str = "Hello World";
int len = str.size();
cout << "String length is " << len << "." << endl;
return 0;
}
七、c聲明字元串
C語言中,字元串是字元數組,可以使用字元串字面量來初始化。
char str[] = "Hello World";
在C++中,可以使用string類型來表示字元串,可以使用字元串字面量或構造函數進行初始化。如:
string str1 = "Hello World";
string str2("Hello World");
八、c聲明結構體
C語言中,聲明結構體需要使用關鍵字struct。如:
struct Student {
int id;
char name[20];
int age;
};
在C++中,可以在struct關鍵字前添加類關鍵字class。如:
class Student {
public:
int id;
string name;
int age;
};
九、c聲明定義
C語言中,聲明變數需要在前面添加關鍵字extern。如:
extern int a;
同樣,在C++中也可以使用關鍵字extern進行聲明,但其默認為外部鏈接。如:
extern int a;
int main() {
a = 10;
return 0;
}
此時,a變數已在其他地方定義。
十、c聲明外部變數
C語言中,使用關鍵字extern聲明外部變數。如:
extern int a;
在C++中同樣可以使用關鍵字extern聲明外部變數,但它與C語言中的用法有所不同。如:
在test.cpp文件中定義一個變數a:
int a = 10;
在main.cpp文件中使用變數a:
#include <iostream>
extern int a;
int main() {
std::cout << "a=" << a << std::endl;
return 0;
}
需要在main.cpp中使用extern關鍵字聲明變數a,以便編譯器在鏈接時能夠找到該變數的定義。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/154324.html
微信掃一掃
支付寶掃一掃