C++ 結構體 給變量賦值 (內部寫構造函數)和 重定義小於號

typedef struct Test{
    int id;
    string name;
    // 用以不初始化就構造結構體
    Test(){} ;
    //只初始化id
    Test(string _name) {
        name = _name;
    }
    //同時初始化id,name 
    Test(inr _id,string _name): id(_id),name(_name)}{};
};
#include<iostream>
#include<string>

using namespace std;

typedef struct Test{
    int id;
    int name;
    // 用以不初始化就構造結構體
    Test(){} ;
    //只初始化id
    Test(int _name) {
        name = _name;
    }
    //同時初始化id,name 
    Test(int _id,int _name): id(_id),name(_name){};
}Test; 

Test test[10];
int main(){
    int a,b,num,i;
    for(a=1,b=1,num=0;b<=10;a++,b++,num++){
        test[num] = Test(a,b);
    }
    for(i=0; i<10;i++)
        cout<<test[i].id<<" "<<test[i].name<<endl;
    return 0;
}

 

 

 

 

 



1.首先你要知道node這個結構體是你自己定義的,計算機並不知道它怎麼去創建變量,所以要你寫一個構造函數讓計算機明白怎麼樣去創建(如果不創建的話,系統會創建一個默認的構造函數).

2.比如這裏的node(const int a=0,const int g= 0):a(a)g(g){} 這個構造函數,就告訴了計算機,你可以這樣創建 : node tmp(1,2);

3.關於運算符重載,因爲這個node類型是你自己定義的,計算機並不知道<是根據什麼來比較大小的,如果你要這樣用
node a,b;
a<b;
就得讓計算機知道當 <左右兩邊是node類型的值的時候,是根據什麼邏輯來返回值的,比如 1<3這個是根據實數的大小來返回真假。

4.可能運算符重載這樣的寫法你看不懂,一般雙目運算符有兩種寫法:
bool operator <(const node &num1){}
bool operator <(const node &num1,const node num2){}
前者是默認 本身是 '<'左邊的項,num1是'<'右邊的項。形如 this < num1
後者是num1 是'<'左邊的項,num2是'<'右邊的項。形如 num1 < num2

node v= node(a[i],g[i]);
就相當於:
node tmp(a[i],g[i]);
node v = tmp;

 


 

第一種

struct D
{
    double len;
    int head,tail;
    D(int a=0,int b=0,double l=0)
    {
        head=a;  tail=b;
        len=l;
    }
};

第二種

struct D
{
    double len;
    int head,tail;
    D(int a,int b,double l)
    {
        head=a;  tail=b;
        len=l;
    }
};

第二種 在申請變量時 容易出問題 這個變量一出生就要知道 內部元素的具體值。

比如

D mid;

mid.head=1;

這時第一種 已經初始化 D(int a=0,int b=0,double l=0)  所以沒有問題

第二種 沒有初始化,並且 一申請出這個 mid 變量就要給它賦值的

可以這樣 D mid = (原來有的 D類型的變量) 或者用構造函數。

#include<bits/stdc++.h>
using namespace std;
struct D
{
    int head,tail;
    double len;
    D(int a,int b,int l)
    {
        head=a;tail=b;len=l;
        cout<<head<<tail<<len<<endl;
    }
};
int main()
{
    int n;
    D mid=D(1,2,3);

    return 0;
}

如果要放到容器裏,自己先規定怎麼排序啊 

而且 這裏只有一個變量   const node & a

在寫sort 的cmp 的時候  會有兩個變量,

不知道爲什麼 ,,先記住了

下面的 bool operator < (const node & a) const   

第一個const  是保證 a 不發生改變,  第二個是保證 函數不發生改變


struct node
{
    int x,y;
    bool operator < (const node & a) const
    {
        return x>a.x;
    }
}k;

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章