1. 程式人生 > 其它 >Linux C++學習第一天 C與C++區別認識

Linux C++學習第一天 C與C++區別認識

技術標籤:c++程式語言vim

C++中很多不同於C的部分。
標頭檔案中<stdio.h>變為<iostream>很多.h檔案中的.h都沒了。
要使用名稱空間;
using namespace std;//標準名稱空間

#include <iostream> //包含標頭檔案  輸入輸出流

using namespace std;  //使用標準名稱空間

int main()
{
	cout << "helloworld" << endl; //cout 標準輸出流物件 << 輸出運算子 endl 換行
	return 0;
}


標準名稱空間中包含cout,endl等定義在名稱空間的內容,當你需要呼叫這些內容卻沒包含名稱空間時需要加上std::作用限定符
例如:std::cout << "helloworld" << std ::endl;
同時在函式內如果定義或者本身有的名稱空間內有相同的定義的函式內容,此時如果呼叫了兩個名稱空間可能在下面函式呼叫時出現函式過載報錯

#include <iostream>

//using namespace std;

namespace A
{
	int a = 1;
	void print()
	{
		std::cout << "this is namespace A" << std::endl; //::作用域限定符
	}
}

namespace B
{
	int a = 2;
	void print()
	{
		std::cout << "this is namespace B" << std::endl;
	}
}

int main()
{
	//std::cout << a << std::endl; // a不是全域性變數也不是main函式區域性變數 所以未定義
	std::cout << A::a << std::endl;

	using namespace B;//接下來沒有作用限定的程式碼都出自這個名稱空間
	std::cout << a << std::endl;
	
	print();

	A::print();

	//using namespace A; //只能使用一個名稱空間

	print();
	return 0;
}

register 在C中用於宣告暫存器變數 不能取地址 &。
但是在C++中用register宣告的變數是可以取地址的。

#include <stdio.h>

int main()
{
	register int i = 0;//宣告暫存器變數 不能取地址

	for (i = 0; i < 1000; i++)

	&i; //C++ 對暫存器變數取地址 register 關鍵字無效

	return 0;
}

在C中結構體定義結構體變數時要加struct, 而在C++中可以不用

#include <stdio.h>

struct Test
{
	int a;
};

int main()
{
	struct Test t;
	 Test t2; //C語言不支援 C++支援
		
	return 0;
}

三目運算子中,例如
num = (a > b) ? a : b;C中num返回的是某個a,b某個變數的值。而在C++中返回的是某個變數

#include <stdio.h>

int main()
{
	int a = 1, b = 2;

	int num = (a > b) ? a : b;

	printf("%d\n", num);

	//(a > b) ? a : b = 100; //C語言中, 返回的是具體的數值(2 = 100)   C++中, 返回的是變數名(b = 100) 

	return 0;
}

void f()C中表示接受任意引數。C++不能

在Linux中C語言編譯時gcc,C++是g++